/**
 *
 *	Depends on:
 *		jQuery
 *		jQuery UI
 */
$(document).ready(function() {

	//Selectors
	var FORM = $('#question-form');
	var FORM_INPUTS = FORM.find(':input');
	var FORM_CONTROLS = FORM_INPUTS.closest('.control-group');
	var FORM_INFO_ICONS = FORM.find('.icon-info-sign');
	var RESULT = $('#result');
	var SUBMIT_BUTTON = $('#submit');
	var RETAKE_BUTTON = $('#retake');

	/* Listeners */
	SUBMIT_BUTTON.on('click', function(event) {
		
		// Prevent default posting of form
		event.preventDefault();
		
		// Abort any pending request
		if (request) {
			request.abort();
		}

		// Serialize the data in the form
		var serializedData = FORM.serialize();

		// Disable the inputs for the duration of the ajax request
		FORM_INPUTS.prop("disabled", true);

		// Send the request to the forms action path
		var request = $.post(
			FORM.attr('action'), 
			serializedData, 
			'json'
		);

		// Callback handler that will be called on success
		request.done(function (response, textStatus, jqXHR){	
			viewCorrectedTest(response);
		});

		// Callback handler that will be called on failure
		request.fail(function (jqXHR, textStatus, errorThrown){
			// log the error to the console
			console.error("The following error occured: " + 
				textStatus, errorThrown
			);
			// TODO: Handle error, bad request etc.
		});

		// Callback handler that will be called regardless
		// if the request failed or succeeded
		request.always(function () {
			// Reenable the inputs
			FORM_INPUTS.not(SUBMIT_BUTTON).prop("disabled", false);
		});
	
	});
	
	RETAKE_BUTTON.on('click', function(event) {
		// Prevent default posting of form
		event.preventDefault();

		// Disable the inputs for the duration of the reset
		FORM_INPUTS.prop("disabled", true);

		// Resets the form and reloads the page
		FORM[0].reset();
		location.reload();

		// Reenable the inputs
		FORM_INPUTS.prop("disabled", false);
		
	});


	/**
	 *	Colour codes the test using the given corrected test. Also adds the 
	 *  hint information if available and displays the number of correct
	 *  answers and total number of questions
	 */
	function viewCorrectedTest(correctedTest) {

		numberOfCorrectAnswers = 0;
		FORM_CONTROLS.each(function() {
			// "Id" of the inputelement that will be colour coded
			var name = $(this).find('.controls').attr('name');
			var isCorrect = correctedTest[name][0];
			var infoIcon = $(this).find('.icon-info-sign');

			// Add hint as popover
			if (correctedTest[name][1]) {
				infoIcon.popover({
					trigger: 'hover', 
					placement: 'bottom', 
					content: correctedTest[name][1]
				});
			} else {
				infoIcon.remove(); // Ugly
			}

			// Colour coding of the answer elements
			if (isCorrect) {
				$(this).addClass('success');

				if ($(this).find('input:radio').length) {
					$(this).find('input:checked').next('span').addClass('text-success');
				}
				numberOfCorrectAnswers++;
			} else {
				$(this).addClass('error');

				if ($(this).find('input:radio').length) {
					$(this).find('input:checked').next('span').addClass('text-error');
				}
			}

		});

		// Help method to count number of elements in an array
		$.assocArraySize = function(obj) {
			var size = 0, key;
			for (key in obj) {
				if (obj.hasOwnProperty(key)) size++;
			}
			return size;
		};

		// Shows number of correct answers and total number of questions
		RESULT.html(numberOfCorrectAnswers + "/" + $.assocArraySize(correctedTest));

		// Show all info icons and the result info box
		FORM_INFO_ICONS.css('display', 'inline-block');
		RESULT.show();
	}

	
});